package com.datasync.core;

import java.time.LocalDateTime;

public interface CheckpointRepository {
    void saveCheckpoint(String jobId, LocalDateTime checkpoint);
    LocalDateTime getLastCheckpoint(String jobId);
}

@Repository
class JdbcCheckpointRepository implements CheckpointRepository {
    private final JdbcTemplate jdbcTemplate;

    @Autowired
    public JdbcCheckpointRepository(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    @Override
    public void saveCheckpoint(String jobId, LocalDateTime checkpoint) {
        jdbcTemplate.update("MERGE INTO sync_checkpoints (job_id, last_sync_time) VALUES (?, ?)",
                jobId, Timestamp.valueOf(checkpoint));
    }

    @Override
    public LocalDateTime getLastCheckpoint(String jobId) {
        return jdbcTemplate.queryForObject(
                "SELECT last_sync_time FROM sync_checkpoints WHERE job_id = ?",
                new Object[]{jobId},
                (rs, rowNum) -> rs.getTimestamp("last_sync_time").toLocalDateTime()
        );
    }
}